package com.example.test02mybatisplus.service;

import com.alibaba.excel.util.DateUtils;
import com.example.test02mybatisplus.entity.domain.User;
import com.example.test02mybatisplus.exception.Exception1;
import com.example.test02mybatisplus.exception.Exception2;
import com.example.test02mybatisplus.exception.Exception3;
import com.example.test02mybatisplus.mapper.UserMapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: fxy
 * @Date: 2021/12/27/10:58
 * @Description:
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    @Lazy
    UserService userService;
    @Transactional(rollbackFor = Exception1.class)
    public void rollBackTest1() throws Exception{
        User user = new User();
        user.setId("1");
        user.setName("rollBackTest1");
        userMapper.updateById(user);
        throw new Exception1("exception1");
    }

    @Transactional(rollbackFor = Exception2.class,noRollbackFor = Exception1.class)
    public void rollBackTest2() throws Exception{
        User user = new User();
        user.setId("1");
        user.setName("rollBackTest2");
        userMapper.updateById(user);
        throw new Exception1("exception1");
    }

    @Transactional(rollbackFor = Exception.class,noRollbackFor = {Exception3.class,Exception2.class})
    public void rollBackTest3() throws Exception{
        User user = new User();
        user.setId("1");
        user.setName("rollBackTest3");
        userMapper.updateById(user);
        try {
            this.divideZero();
        }catch (Exception e){
            throw new Exception3("exception3");
        }

        throw new Exception3("exception3");
    }

    private void divideZero() {
        int i = 1/0;
    }

    public void wayOutTest1() throws Exception {
        userService.methodInTransaction();
    }

    public void wayOutTest2() throws Exception {
        this.methodInTransaction();
    }

    @Transactional(rollbackFor = Exception.class)
    public void methodInTransaction() throws Exception {
        User user = new User();
        user.setId(DateUtils.format(new Date()));
        user.setName("methodInTransaction");
        userMapper.insert(user);
        //throw new Exception("Exception");
    }
}
